package com.order.config;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

public class CustomRule extends AbstractLoadBalancerRule {
    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {

    }

    @Override
    public Server choose(Object key) {
        //获得所有实例
        ILoadBalancer loadBalancer=this.getLoadBalancer();//获得负载均衡器
        List<Server> reachableServers = loadBalancer.getReachableServers();//可获得的实例
        int random = ThreadLocalRandom.current().nextInt(reachableServers.size());//在实例的长度中随机选择一个数
        Server server=reachableServers.get(random);//根据下标取得实例
        return server;
    }
}
